package com.ratingbay.console.restful;

import java.util.*;
import java.io.*;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ratingbay.console.databean.GameAboutDataBean;
import com.ratingbay.console.dataface.*;
import com.ratingbay.console.model.*;
import com.ratingbay.console.restful.builder.*;

@Controller
@RequestMapping("/rest/twitterUser")
public class TwitterUserRestful extends BaseRestful{

    @RequestMapping(value="/searchUsers/{uName}/{page}", method=RequestMethod.GET)
    public @ResponseBody 
    Map getRecentActiveGamers(@PathVariable String uName, @PathVariable int page){
        Page<ITwitterUser> searchUsers = getTUserApi().getUsersByName(uName, page, 5);
        return decoratTwitterUser(searchUsers, page);
    }
    @RequestMapping(value="/searchOrderedUsers/{uName}/{f}/{d}/{page}", method=RequestMethod.GET)
    public @ResponseBody 
    Map getRecentActiveOrderedGamers(@PathVariable String uName, @PathVariable String f, @PathVariable String d, @PathVariable int page){
        Page<ITwitterUser> searchUsers = getTUserApi().getUsersByName(uName, f, d, page, 5);
        return decoratTwitterUser(searchUsers, page);
    }

    @RequestMapping(value="/getUserWaters/{uName}/{page}", method=RequestMethod.GET) 
    public ModelAndView getUserWaters(@PathVariable String uName, @PathVariable int page){
        
        Page<ITwitterUser> searchUsers = getTUserApi().getUsersByName(uName, page, 5);
       
        ModelMap model = new ModelMap();
        model.addAttribute( "userList", searchUsers.getContent() );
        model.addAttribute( "IRestfulViewContentBuilder", 
            new WaterBuilderImpl() );

        Map<String, Object> retMap = new HashMap();
        retMap.put( "hasNext", searchUsers.hasNextPage());
        model.addAttribute( "retMap", retMap );

        return new ModelAndView("restful/userWater", model);
    }
    @RequestMapping(value="/getOrderedUserWaters/{uName}/{f}/{d}/{page}", method=RequestMethod.GET) 
    public ModelAndView getOrderedUserWaters(@PathVariable String uName, @PathVariable String f, @PathVariable String d, @PathVariable int page){
        
        Page<ITwitterUser> searchUsers = getTUserApi().getUsersByName(uName, f, d, page, 5);
       
        ModelMap model = new ModelMap();
        model.addAttribute( "userList", searchUsers.getContent() );
        model.addAttribute( "IRestfulViewContentBuilder", 
            new WaterBuilderImpl() );

        Map<String, Object> retMap = new HashMap();
        retMap.put( "hasNext", searchUsers.hasNextPage());
        model.addAttribute( "retMap", retMap );

        return new ModelAndView("restful/userWater", model);
    }
    
    @RequestMapping(value = "/getUserActionWater/{userId}/{page}" , method = RequestMethod.GET)
	public @ResponseBody
	Map getUserActionWater(@PathVariable Long userId,@PathVariable int page){
		Page<Game> userGame = getGameApi().getGamebyUser(userId, page, 5);
		PageRequest pageRequest = new PageRequest(page, 5);
		
		List<Long> utUserIds = new ArrayList<Long>();
		utUserIds.add(userId);
		List<GameAboutDataBean> gameAboutData = new ArrayList<GameAboutDataBean>();
		Iterator<Game> it = userGame.iterator();
		Game tmpGame = null;
		GameAboutDataBean tGADB = null; 
		while(it.hasNext()){
			tmpGame = it.next();
			tGADB = new GameAboutDataBean();
			tGADB.gameDetail = getGameApi().getGameDetail( tmpGame.getId() );
			tGADB.gameDetail.setTweetCount( getTweetApi().getTweetCountByGame( tmpGame.getId() ) );
            tGADB.latestTweets = getTweetApi().getUsersTweetsByGame( tmpGame.getId(), utUserIds, 0, 5 );
			tGADB.gameUserId = userId;

            gameAboutData.add(tGADB);
		}
		Long ll = getTweetApi().getGameCountByUser(userId);
		Page<GameAboutDataBean> pageGameAboutData = new PageImpl<GameAboutDataBean>(gameAboutData,pageRequest,ll);
		
		return decoratTwitterUserGame(pageGameAboutData,page);	
	}


    protected Map decoratTwitterUserGame(Page<GameAboutDataBean> pageGameAboutData,
			int page) {
    	Map dataJson = new HashMap<String, Object>();
        List result = new ArrayList<Map>();

        Iterator<GameAboutDataBean> it = pageGameAboutData.iterator();
        GameAboutDataBean tUser; 
        Map resultOne;
        Map latesTweetOne;
        List<Object> latesTweet;
        while(it.hasNext()){
            tUser = it.next();
            
            resultOne = new HashMap<String, Object>();
            resultOne.put("id", tUser.gameDetail.getId());
            resultOne.put("gameUserId", tUser.gameUserId);
            resultOne.put("tweetCount", tUser.gameDetail.getTweetCount());
            resultOne.put("dvdImagePath", tUser.gameDetail.getDvdImagePath());
            resultOne.put("score", tUser.gameDetail.getScore());
            resultOne.put("title", tUser.gameDetail.getTitle());
            
            latesTweet = new ArrayList<Object>();
            Iterator<Tweet> t = tUser.latestTweets.iterator();
            while(t.hasNext()){
            	Long i = t.next().getId();
            	String id = String.valueOf(i);
            	latesTweetOne = new HashMap<String, Object>();
            	latesTweetOne.put("id", id);
            	latesTweet.add(latesTweetOne);
            }
            resultOne.put("latestTweet", latesTweet);
            result.add(resultOne);
        }
        
        dataJson.put("result", result);
        dataJson.put("status", 1);
        dataJson.put("page", page);
        dataJson.put("hasNext", pageGameAboutData.hasNextPage());
        
        return dataJson;
	}
	//used in class inner
    protected Map decoratTwitterUser(Page<ITwitterUser> tUsersOfPage, int page){
        Map dataJson = new HashMap<String, Object>();
        List result = new ArrayList<Map>();

        Iterator<ITwitterUser> it = tUsersOfPage.iterator();
        ITwitterUser tUser; 
        Map resultOne;
        while(it.hasNext()){
            tUser = it.next();
            
            resultOne = new HashMap<String, Object>();
            resultOne.put("id", tUser.getId());
            resultOne.put("username", tUser.getUsername());
            resultOne.put("tweetsCount", tUser.getTweetsCount());
            resultOne.put("gameCount", tUser.getGameCount());
            resultOne.put("profileImageURL", tUser.getProfileImageURL());
            resultOne.put("rescription", tUser.getDescription());
            resultOne.put("location", tUser.getLocation());
            resultOne.put("followersCount", tUser.getFollowersCount());
            resultOne.put("friendsCount", tUser.getFriendsCount());

            result.add(resultOne);
        }
        
        dataJson.put("result", result);
        dataJson.put("status", 1);
        dataJson.put("page", page);
        dataJson.put("hasNext", tUsersOfPage.hasNextPage());
        
        return dataJson;
    }
}